/**
 *  版权所有 Copyright@2016-3-28下午6:18:34
 */
package com.fairy.sso.core;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

/**
 * [NetHelp.java.java]
 *
 * @Author: [yyk1504@163.com]
 * @CreateDate: [2016-3-28下午6:18:34]
 * @Update: [说明本次修改内容] by [yyk1504@163.com] [2016-3-28下午6:18:34]
 * @Version: [v1.0]
 */
public class NetHelp {

	/**
	 * <p>判断是否为ip地址</p>
	 * @param addr
	 * @return
	 */
	 public static boolean isIP(String addr)
     {
	      if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))
	      {
	        return false;
	      }
	      /**
	       * 判断IP格式和范围
	       */
	      String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
	      
	      Pattern pat = Pattern.compile(rexp);  
	      
	      Matcher mat = pat.matcher(addr);  
	      
	      boolean ipAddress = mat.find();
	
	      return ipAddress;
     }
	/**
	 * <p>获取域名，如：http://f0rb.iteye.com/ </p>
	 * @param request
	 * @return
	 */
	public static String getDomainOrIP(HttpServletRequest request)
	{
		String   url  = request.getRequestURL().toString();
		url=url.toLowerCase();
		url=url.replace("http://", "");
		int index=url.indexOf("/");
		if(index!=-1)
		{
			url=url.substring(0, index);
		}
		int index2=url.indexOf(":");
		if(index2!=-1)
		{
			url=url.substring(0, index2);
		}		
		
		return url;
	}
	/**
	 * <p>获取域名，如：http://f0rb.iteye.com/ </p>
	 * @param request
	 * @return
	 */
	public static String getDomain(HttpServletRequest request)
	{
		StringBuffer url = request.getRequestURL();  
		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
		
		return tempContextUrl;
	}
	
	/**
	 * <p>获得.a.com类似域名</p>
	 * @param url
	 * @return
	 */
	public static String getDomainWithout3W(String url)
	{
		//String url = http://www.linuxidc.com/entry/4545/0/;
		Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",Pattern.CASE_INSENSITIVE);
		Matcher matcher = p.matcher(url);
		String domain="";
		while(matcher.find())
		{
			domain=matcher.group();
		}
		return domain;
	}
	public static String getDomain(String  url)
	{
		String str="";
		url=url.toLowerCase();
		url=url.replace("http://", "");
		int index=url.indexOf("/");
		if(index!=-1)
		{
			str=url.substring(0, index);
			int index1=str.lastIndexOf(":");
			if(index1!=-1)
			{
                str=str.substring(0, index1);
			}
			
		}

		return str;
	}
	/**
	 * <p>获取带部署环境上下文的域名，如： http://www.iteye.com/admin/ </p>
	 * @param request
	 * @return
	 */
	public static String getDomainName(HttpServletRequest request)
	{
		StringBuffer url = request.getRequestURL();  

		String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getContextPath()).append("/").toString(); 
		return tempContextUrl;
	}
	/**
	 * <p>获取带部署环境上下文的域名，如： http://www.iteye.com/admin/ </p>
	 * @param request
	 * @return
	 */
	public static String getAgent(HttpServletRequest request)
	{
		String agent = request.getHeader("user-agent");

		return agent;
	}

	/**
	 * <p>获得 请求的header信息 </p>
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> getHeadersInfo(HttpServletRequest request) 
	{
	    Map<String, String> map = new HashMap<String, String>();
	    Enumeration<String> headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	        String key = headerNames.nextElement();
	        String value = request.getHeader(key);
	        map.put(key, value);
	    }
	    return map;
	}
	/**
	 * 判断ajax请求
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request){
	    return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
	}
	
	public static InetAddress getInetAddress(){  
		  
        try{  
            return InetAddress.getLocalHost();  
        }catch(UnknownHostException e){  
            System.out.println("unknown host!");  
        }  
        return null;  
  
    }  
	/**
	 * <p>获得本机Ip</p>
	 * @param netAddress
	 * @return
	 */
	 public static String getLocalHostIp(){ 
		 //String os = System.getProperty("os.name");  
		 String localIp="";
		 localIp=getHostIp(getInetAddress());
		 /**
		 if(os.toLowerCase().startsWith("win")){  
			 localIp=getHostIp(getInetAddress());
		 }
		 else
		 {
			 Enumeration<?> allNetInterfaces;
			try {
				allNetInterfaces = NetworkInterface.getNetworkInterfaces();
				 InetAddress ip= null;
				 while (allNetInterfaces.hasMoreElements())
				 {
					 NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
					 System.out.println("========================getLocalHostIp::netInterface.getName()::::"+netInterface.getName()+"===========================");
					 Enumeration<?> addresses = netInterface.getInetAddresses();
					 while (addresses.hasMoreElements())
					 {
						 ip = (InetAddress) addresses.nextElement();
						 if (ip != null && ip instanceof Inet4Address)
						 {
							 localIp=ip.getHostAddress();//System.out.println("本机的IP = " + ip.getHostAddress());
						 } 
					 }
				 }
			} catch (SocketException e) {
				e.printStackTrace();
			}

		 }*/

	        return localIp;  
	    }  
	
    public static String getHostIp(InetAddress netAddress){  
        if(null == netAddress){  
            return null;  
        }  
        String ip = netAddress.getHostAddress(); //get the ip address  
        return ip;  
    }  
  
    public static String getHostName(InetAddress netAddress){  
        if(null == netAddress){  
            return null;  
        }  
        String name = netAddress.getHostName(); //get the host address  
        return name;  
    }  
	public static void main(String[] args)
	{
		String str="http://192.169.1.161/admin";
		System.out.println(getDomain(str));
	}
}
